import{bx as x,by as B,p as b,bz as A,U as _,bA as Z,bB as N,bC as U,bD as X,bE as W,E,s as y,a7 as H,bF as V}from"./DrFvzlh8agutd.js";import{S as M,aa as G,T as q,R as K,ab as v,K as Y}from"./MpnPZlTSagutd.js";import{T as J}from"./CRB7nLEs3hcpv4.js";import{b as Q,c as j,a as tt}from"./DZFz6IIX1esOcA.js";import{g as et,p as nt}from"./Ba8fE4Bu4swc5U.js";const st=new x(String.raw`
  (
    (?:
        (?:
          rechnungs? |
          bestell |
          bestellungs? |
          auftrags? |
          lieferungs? |
          liefer |
          kunden? |
          auftragsbestätigungs? |
          auftrags?
        )[\s-]?(?:
          nr\.? | 
          nummer
        )? 
        |
        (?:
          orders? |
          customers? |
          clients? |
          invoices? |
          transactions? |
          billings?
        )[\s-]?(?:
          nr\.? |
          id | 
          no\.? |
          number
        )?
        |
        factures?[\s-]?(?:
          nr\.? |
          no\.? |
          number
        )?
    )
    \s*
    [^\w\d\n\t]*
    \s+
    [#]?
  )  
  (
    [\d\w\-\_\ \/\\]+
  )
  `,"gimx");function ot(s){return st.execAll(s).map(t=>{const e=t[2];if(!e||typeof e!="string"||!/\d/.test(e))return;const o=e.length;return{type:"identifier",range:[t.index+t[1].length,o],value:e}}).filter(M)}const it=String.raw`
(?<![\d\,\.\/])
(?P<sign>\-)?
(?P<integer>
  \d+
  (?:[\,\.]\d+)?
)
\s*\%
(?![\d\,\.\/])
`,rt=new x(it,"gmix");function at(s){return s=B(s,"'-"),rt.execAll(s).map(t=>{const e=t[0].length,n=[+t.index,e],i=t.group.integer.replace(/[^\d]/gim,"");typeof t.group.rest=="string"&&(t.group.rest.length===1||t.group.rest.length);const r=(t.group.rest||"").replace(/[^\d]/,""),a=t.group.sign==="-";let d=`${a?"-":""}${i}`;return r&&(d+=`.${r}`),{type:"percent",range:n,value:+d,string:t[0],negative:a}})}const ct=new x(/(\d\d\d)\ *\/\ *(\d\d\d\d)\ *\/\ *(\d\d\d\d\d?)/,"gm");function lt(s){return ct.execAll(s).map(t=>{const e=+t.index,o=t[0].length,n=`${t[1]}/${t[2]}/${t[3]}`;return{type:"taxid",range:[e,o],value:n}})}const dt=b("extract-lines",!1);function C(s,t){const{mergeOverlaps:e=!0,removeBlockSpaces:o=!0,keepSorting:n=!1}=t??{};s=G(s);let i="",r=[];if(s?.length){if(o)for(const c of s){const f=c.text.trim().replace(/\s/gm,"");f.length*2-1===c.text.length&&(c.text=f)}n||s.sort((c,f)=>c.box.y-f.box.y||c.box.x-f.box.x);let a=[],d=0;for(const c of s)c.box.y>=d&&(d=c.box.y+c.box.h*.5,a.length>0&&r.push(a),a=[]),a.push(c);if(a&&a.length&&r.push(a),!n)for(const c of r)c.sort((f,u)=>f.box.x-u.box.x);e&&(r=r.map(c=>{const f=[];for(const u of c){if(f.length>0){const l=q(f),h=l.box.w/l.text.length*.01,g=l.box.x+l.box.w;if(u.box.x-g<=h){l.box.w+=u.box.x-g+u.box.w,l.text+=u.text;continue}}f.push(u)}return f})),s=r.flat(1),i=r.map(c=>{let f=0;return c.map(u=>{const l=5*(u.box.w/u.text.length),g=Math.abs(u.box.x-f)>l?"	":" ";return f=u.box.x+u.box.w,g+u.text}).join("").slice(1)}).join(`
`),dt(`Extracted Text:
${i}`)}return{lines:r,text:i,items:s}}const ft=new x(String.raw`
  (
    (
      [\w\d$&+_\-\.]+
      |
      \" [\w\d$&+_\-\.]+ \"
    )
    @
    (
      [a-zA-Z0-9\-]+
      ( \. [a-zA-Z0-9\-]+ )*
      |
      \[  [a-zA-Z0-9\-\.\:]+ \]
    )
  )`,"gmx");function ut(s){return ft.execAll(s).map(t=>{const e=t[1].replace(/\.$/,""),o=t[1].length;return{type:"email",range:[+t.index,o],value:e}})}const ht=b("phone"),gt=String.raw`
(?<!\d\ *)
(
  \(?
  (\+|00|0)?
  (
    [\ \t\-\(\)\.\/]*
    [1-9]
    (
      [\ \t\-\(\)\.\/]*
      [0-9]
    ){7,64}
  )
)
(?!\ *\d)
`,k=new x({rx:/(\(?(\+|00|0)?([\ \t\-\(\)\.\/]*[1-9]([\ \t\-\(\)\.\/]*[0-9]){7,64}))(?!\ *\d)/gm,namedGroups:{},lookBehind:{rx:/\d\ *$(?!\s)/,expect:!1}}),S=A?k:new x(gt,"gmx");if(!A){const s=S.equals(k);s||console.log("const RX_RAW =",S.toSmartRegexpCall()),ht.assert(s,"Requires update of RAW regexp #phone")}function xt(s,t){const{onlyInternational:e=!0}={};return S.execAll(s).map(o=>{const n=o[0].replace(/^\s/gm,""),i=n.trim(),r=+o.index+(o[0].length-n.length),a=n.length,d=i.replace(/^00/,"+").replace("(0)","").replace(/[^\d+]/gm,"");if(!(d.length>=32)&&!(e&&!d.startsWith("+")))return{type:"phone",range:[r,a],value:d,string:i}}).filter(M)}const pt=new x(/((?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u00A1-\uFFFF][a-z0-9\u00A1-\uFFFF_-]{0,62})?[a-z0-9\u00A1-\uFFFF]\.)+(?:[a-z\u00A1-\uFFFF]{2,}\.?))(?::\d{2,5})?(?:[/?#]\S*)?)/,"gm");function mt(s){return pt.execAll(s).map(t=>{let e=t[0];e.endsWith(")")&&(e=e.slice(0,-1));const o=e.length;return{type:"url",range:[+t.index,o],value:e}})}const wt=b("vatid"),bt=String.raw`
(?<![\w])                                      # No char before
(
  (AT)U[0-9]{8} |                              # Austria
  (BE)0[0-9]{9} |                              # Belgium
  (BG)[0-9]{9,10} |                            # Bulgaria
  (HR)[0-9]{11} |                              # Croatia
  (CY)[0-9]{8}[A-Z] |                          # Cyprus
  (CZ)[0-9]{8,10} |                            # Czech Republic
  (DE)[0-9]{9} |                               # Germany
  (DK)[0-9]{8} |                               # Denmark
  (EE)[0-9]{9} |                               # Estonia
  (EL)[0-9]{9} |                               # Greece
  (ES)[A-Z][0-9]{7}(?:[0-9]|[A-Z]) |           # Spain
  (FI)[0-9]{8} |                               # Finland
  (FR)[0-9A-Z]{2}[0-9]{9} |                    # France
  (GB)([0-9]{9}([0-9]{3})?|[A-Z]{2}[0-9]{3}) | # United Kingdom
  (HU)[0-9]{8} |                               # Hungary
  (IE)[0-9]{7}[A-Z]{1,2}   |                   # Ireland
  (IE)[0-9][A-Z][0-9]{5}[A-Z] |                # Ireland (2)
  (IT)[0-9]{11} |                              # Italy
  (LT)([0-9]{9}|[0-9]{12}) |                   # Lithuania
  (LU)[0-9]{8} |                               # Luxembourg
  (LV)[0-9]{11} |                              # Latvia
  (MT)[0-9]{8} |                               # Malta
  (NL)[0-9]{9}B[0-9]{2} |                      # Netherlands
  (PL)[0-9]{10} |                              # Poland
  (PT)[0-9]{9} |                               # Portugal
  (RO)[0-9]{2,10} |                            # Romania
  (SE)[0-9]{12} |                              # Sweden
  (SI)[0-9]{8} |                               # Slovenia
  (SK)[0-9]{10} |                              # Slovakia
  (CHE)-[0-9]{3}\.[0-9]{3}\.[0-9]{3}           # Switzerland UID (not really VAT!) https://de.wikipedia.org/wiki/Unternehmens-Identifikationsnummer    
)
(?!\ *\d)                                      # No more numbers
`,P=new x({rx:/((AT)U(\s*\d){8}|(BE)0(\s*\d){9}|(BG)(\s*\d){9,10}|(HR)(\s*\d){11}|(CY)(\s*\d){8}[A-Z]|(CZ)(\s*\d){8,10}|(DE)(\s*\d){9}|(DK)(\s*\d){8}|(EE)(\s*\d){9}|(EL)(\s*\d){9}|(ES)[A-Z](\s*\d){7}(?:(\s*\d)|[A-Z])|(FI)(\s*\d){8}|(FR)[0-9A-Z]{2}(\s*\d){9}|(GB)((\s*\d){9}((\s*\d){3})?|[A-Z]{2}(\s*\d){3})|(HU)(\s*\d){8}|(IE)(\s*\d){7}[A-Z]{1,2}|(IE)(\s*\d)[A-Z](\s*\d){5}[A-Z]|(IT)(\s*\d){11}|(LT)((\s*\d){9}|(\s*\d){12})|(LU)(\s*\d){8}|(LV)(\s*\d){11}|(MT)(\s*\d){8}|(NL)(\s*\d){9}B(\s*\d){2}|(PL)(\s*\d){10}|(PT)(\s*\d){9}|(RO)(\s*\d){2,10}|(SE)(\s*\d){12}|(SI)(\s*\d){8}|(SK)(\s*\d){10}|(CHE)-(\s*\d){3}\.(\s*\d){3}\.(\s*\d){3})(?!\ *\d)/gm,namedGroups:{},lookBehind:{rx:/[\w]$(?!\s)/,expect:!1}}),T=A?P:new x(bt.replace(/\[0-9\]/g,"(\\s*\\d)"),"gmx");if(!A){const s=T.equals(P);s||console.log("const RX_RAW =",T.toSmartRegexpCall()),wt.assert(s,"Requires update of RAW regexp #vatid")}function yt(s){return T.execAll(s).map(t=>{const e=+t.index,o=t[0].length,n=t[0],i=n.replace(/[^\w\d]/gm,"");return{type:"vatid",range:[e,o],value:i,string:n,country:i?i.substring(0,2).toLowerCase():void 0}})}function F(s,t){return s.x<=t.x&&s.y<=t.y&&s.x+s.w>=t.x+t.w&&s.y+s.h>=t.y+t.h}function L(s){return{l:s.x,t:s.y,r:s.x+s.w,b:s.y+s.h}}function vt(s){return{x:s.l,y:s.t,w:s.r-s.l,h:s.b-s.t}}function At(s,t){const e=L(s),o=L(t);return vt({l:Math.min(e.l,o.l),t:Math.min(e.t,o.t),r:Math.max(e.r,o.r),b:Math.max(e.b,o.b)})}function Rt(s,t){const e=s.x,o=s.x+s.w,n=t.x,i=t.x+t.w,r=s.y,a=s.y+s.h,d=t.y,c=t.y+t.h,f=Math.max(0,e-i,n-o),u=Math.max(0,r-c,d-a);return{dx:f,dy:u,d:Math.sqrt(f*f+u*u)}}const It=["position: fixed","width: 1px","height: 1px","overflow: hidden","padding: 0","margin: 0","clip: rect(1px 1px 1px 1px)","clip: rect(0, 0, 0, 0)","border: 0","display: block","visibility: visible","white: space nowrap"].join(";");let w;function z(){return w}typeof document<"u"&&(w=document.createElement("div"),w.setAttribute("style",It),w.setAttribute("data-creator","hiddenContainer"),document.body.appendChild(w));const St=b("textmeasure");function Tt(s="Helvetica",t=12){St.assert(typeof document<"u","Metrics only work in DOM context.");const e=_(),o=document.createElement("div");return o.setAttribute("style",`position: absolute; font-family: ${s}; font-size: ${t}px; white-space: nowrap;`),o.setAttribute("data-creator","useTextMetricDOM"),z().appendChild(o),e.add(()=>{z().removeChild(o)}),{measure:K(i=>{const r=(i??"").replace(/\s/gi," ");if(r.length<=0)return{w:0,h:0};o.textContent=r;const a=o.getBoundingClientRect();return{w:a.width,h:a.height}}),dispose:e}}function Et(s){return s.reduce((t,e)=>t+e,0)}function Ct(s){return Et(s)/s.length}let I;class Ft{content;page;lines;items;text;textReadable;size;tm;config;mergeOverlaps;removeBlockSpaces;keepSorting;constructor(t,e={}){this.config=e;const{avoidTextMetric:o=!1,mergeOverlaps:n=!0,removeBlockSpaces:i=!0,keepSorting:r=!1,maxPages:a=1}=e;if(this.mergeOverlaps=n,this.removeBlockSpaces=i,this.keepSorting=r,!o&&!I&&(I=Tt()),this.tm=o?void 0:I,this.lines=[],this.items=[],this.text="",this.textReadable="",this.size={w:0,h:0},typeof t=="string"&&(t=JSON.parse(t)),this.content=t,t&&t.pages.length>0&&(this.page=t.pages[0]),this.page){this.size=this.page.size;let d=this.page?.items??[];const c={x:0,y:0,...this.size};d=d.filter(u=>F(c,u.box));const f=C(d,{mergeOverlaps:n,removeBlockSpaces:i,keepSorting:r});this.items=f.items,this.lines=f.lines,this.text=f.text,this.textReadable=this.getLayoutBoxes().map(u=>u.text).join(`

`)}}getChar(t){let e=0;for(const o of this.items){const n=o.text.length+1;if(e<=t&&t<e+n){e=Math.min(t-e,n-1);const r=o.font?.family?.includes("mono")?0:o.box.w/(this.tm?.measure(o.text).w??0)||1,a=o.box.w/o.text.length,d=(this.tm?.measure(o.text.substring(0,e)).w??0)*r||a*e,c=(this.tm?.measure(o.text.substring(0,e+1)).w??0)*r||a*(e+1);return{x:o.box.x+d,y:o.box.y,w:c-d,h:o.box.h}}e+=n}throw new Error("Undefined state")}getBoundingBox(t){const[e,o]=t,n=this.getChar(e),i=this.getChar(e+o);return{x:Math.round(n.x),y:Math.round(n.y),w:Math.round(i.x-n.x),h:Math.round(Math.max(n.h,i.h))}}getLayoutBoxes(){const t=[...this.items].sort((n,i)=>n.box.y-i.box.y||n.box.x-i.box.x),e=1.5*Ct(t.map(n=>(n.box.h||0+n.box.h||0)/2)),o=[];for(const n of t){let i,r=Number.MAX_SAFE_INTEGER;for(const a of o){const d=Rt(a.box,n.box).d;d<e&&d<r&&(i=a,r=d)}i?(i.box=At(i.box,n.box),i.items.push(n)):o.push({box:n.box,items:[n],text:""})}return o.forEach(n=>n.text=C(n.items,{mergeOverlaps:this.mergeOverlaps,removeBlockSpaces:this.removeBlockSpaces,keepSorting:this.keepSorting}).text),o}getInfo(){const{preferMDY:t}=this.config,e=Z(this.text),o=[...N(this.text),...mt(this.text),...ut(this.text),...U(this.text,{preferMDY:t}),...yt(this.text),...xt(this.text),...X(this.text),...lt(this.text),...at(this.text),...ot(this.text),...e.filter(i=>i.decimalPlaces===2).map(i=>({...i}))],n=[];for(const i of o)if(!n.some(r=>W(r.range,i.range))){const r=this.getBoundingBox(i.range);i.box=r,n.push(i)}return n}scoreDates(t){let e=0,o;return t.filter(n=>n.type==="day").forEach(n=>{n.box&&(n.score=(this.size.h-n.box.y)*this.size.w+n.box.x,n.score>e&&(e=n.score,o=n))}),o}scoreIBAN(t){return v(t.filter(e=>e.type==="iban"))?.value}scoreVatId(t){return v(t.filter(e=>e.type==="vatid"))?.value}scoreTaxId(t){return v(t.filter(e=>e.type==="taxid"))?.value}scoreIdentifier(t){return v(t.filter(e=>e.type==="identifier"))?.value}scoreAmounts(t,e=[7,19],o){let r=!1,a=0;const d=t.filter(l=>l.type==="amount");d.forEach(l=>{l?.box?.h;const h=l.box?l.box?.x+l.box?.w:0;h>a&&(a=h),l.right=h,!r&&l.rightPart.length===2&&(r=!0)}),d.forEach(l=>{if(l.score=l.value!==0?.1:0,!l.negative&&l.rightPart.length===2&&!l.after?.trim().startsWith("%")){const h=Math.ceil(l.right/a)*3/3;l.score+=.1*h}});const c=[],f=d.map(l=>+l.value).filter(l=>l>0);for(const l of f)for(const h of e){const g=new J(l);g.testAgainstValues(f,h),g.testAgainstValues(f,h)&&(c.find(p=>p.equals(g))||c.push(g))}if(c?.length>0){const l=E(c,"weight desc","gross desc")?.[0],{gross:h,net:g,tax:p,taxRate:R}=l;return{gross:h,net:g,tax:p,taxRate:R}}const u=E(d,"score desc","value desc")?.[0]?.value??0;return{gross:u,net:u,tax:0}}scoreBuyer(){const t={x:0,y:this.size.h*0,w:this.size.w*.6,h:this.size.h*.45},e=["herr","frau","firma","company","z.hd.","z. hd.","z. h. d.","z. h. d","z. h d","z. h d.","abt.","abteilung","department","department:"];for(const o of this.getLayoutBoxes())if(F(t,o.box)&&o.text.includes(`
`)){const n=o.text.split(`
`).filter(i=>i.length>0&&!e.includes(i.toLocaleLowerCase()));if(n[0].length>0)return n[0]}}}function Lt(s){s.stopPropagation(),s.preventDefault();const t=[],e=s.dataTransfer;if(e){const o=e?.items;for(let n=0;n<(o?.length||0);n++){const i=o[n];if(i==null||i.kind!=="file")continue;const r=i.getAsFile()||e.files[n];r&&t.push(r)}}return t}const zt=/\S/;function Mt(s){return!zt.test(s)}async function kt(s,t=1){const{Util:e}=await et(),o=await s.getPage(t),n=o.getViewport({scale:1}),i=await o.getTextContent({includeMarkedContent:!0}),r=i.items.filter(a=>!Mt(a.str)).map(a=>{try{const d=i.styles[a.fontName],c=e.transform(n.transform,a.transform),f=Math.atan2(c[1],c[0]);if(d.vertical||f!==0)return;const u=c[4];let l=c[5],h=a.width,g=a.height;return l-=g/1.2,h*=n.scale,g*=n.scale,{box:{x:u,y:l,h:g,w:h},text:a.str,font:{size:a.height,family:d.fontFamily}}}catch{}}).filter(a=>a!=null);return{size:{w:n.width,h:n.height},items:r}}const m=b("action-import"),Pt=new Set;async function Zt(s){const t=Lt(s);for(const e of t){if(Pt.has(e.name)){m.info("drop ignore",e.name);return}m("got file",e);const o=await Q(e);if(!o){m.warn("did not make asset");continue}const n=o.bin,i=await y.workspace?.sync?.writeLocalAsset(n);if(!i){m.warn("did not write asset",n,y.workspace?.sync?.writeLocalAsset);continue}const{cid:r,idx:a}=i,d=j(o,r,a),c={_id:Y(),_type:"doc",credit:!1,date:H(),title:d?.name||"?",asset:tt(d),positions:{}};if(d.type==="application/pdf"){const f=await nt(n);try{if(!f){m.warn("did not load pdf",n);continue}const l={pages:[await kt(f)]},h=new Ft(l);if(h){const g=h.getInfo();c.title=h.scoreIdentifier(g)||c.title,c.date=h.scoreDates(g)?.value;const p=Object.values(y.workspace?.settings?.sTaxRates??{})?.map(O=>O.rate),{gross:R,net:D,tax:$}=h.scoreAmounts(g,p);c.gross=R,c.net=D,c.tax=$}}catch(u){m.warn("pdf error",u),V("PDF error",`Did not import PDF due to error: ${String(u)}`);continue}finally{f?.destroy()}}y.workspace?.createItem(c)}}export{Ft as R,Zt as a,kt as e,Pt as i};